package com.msk.common.utils.http;

import com.alibaba.fastjson2.JSONObject;
import com.msk.common.utils.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @desc: http请求工具类
 * @author: zlf
 * @date: 2022-02-28 14:37
 **/
public class HttpRequestUtil {

    public static String doGet(String url, Map<String, String> param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = "";
            String strMes = "";
            for (String str : param.keySet()) {
                strMes += str + "=" + param.get(str) + "&";
            }
            if (StringUtils.isNotEmpty(strMes)) {
                strMes = strMes.substring(0, strMes.length() - 1);
                urlNameString += "?";
                urlNameString += strMes;
            }
            URL realUrl = new URL(url + urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();

            InputStreamReader fReader = new InputStreamReader(connection.getInputStream(),"UTF-8");
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(fReader);

            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public static String sendGet(String path, Map<String, String> param, Map<String, String> headers) {
        HttpGet httpGet = null;
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建uri
        URIBuilder builder = null;
        try {
            builder = new URIBuilder(path);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            httpGet = new HttpGet(uri);
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }

            // 执行请求
            response = httpClient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            throw new RuntimeException("[发送Get请求错误：]" + e.getMessage());
        } finally {
            try {
                httpGet.releaseConnection();
                response.close();
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String sendPost(String url, Map<String, String> map, boolean isJson) {
        String result = "";
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(550000).setConnectTimeout(550000)
                .setConnectionRequestTimeout(550000).build();
        client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();

        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            HttpPost httpPost = new HttpPost(uriBuilder.build());
            httpPost.setHeader("Connection", "Keep-Alive");
            httpPost.setHeader("Charset", "UTF-8");
            if (isJson) {
                httpPost.setHeader("Content-Type", "application/json");
                httpPost.setEntity(new StringEntity(JSONObject.toJSONString(map), "UTF-8"));
            } else {
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
                Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
                    params.add(pair);
                }
                httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            }
            response = client.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                    return result;
                }
            }
        } catch (ClientProtocolException e) {
            throw new RuntimeException("创建连接协议失败" + e);
        } catch (IOException e) {
            throw new RuntimeException("IOException异常失败" + e);
        } catch (Exception e) {
            throw new RuntimeException("请求失败" + e);
        }
        return result;
    }
}
